package {
	import flash.display.*;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.filesystem.*;
	
	public class SaveXMLFile extends MovieClip
	{
		// public objects
		public var oxml:XML; // Original (input) xml, and final (output) xml
		// private objects
		private var file:File;
		private var stream:FileStream;
		// private vars
		private var userID:String, projectID:String;
		
		
		public function SaveXMLFile (file:File, userID:String, projectID:String, oxml:XML)
		{
			this.file = file; this.userID = userID; this.projectID = projectID; this.oxml = oxml;
			this.addEventListener(Event.ADDED, handleAdded);
		}
		private function handleAdded(event:Event):void
		{
			this.removeEventListener(Event.ADDED, handleAdded);
			/// STEP ONE, is there a 
			// is there a file in the application directory
			file = File.applicationStorageDirectory.resolvePath(String("userfiles/"+userID+"_"+projectID+".xml"));
			
			//file = File.applicationDirectory.resolvePath(String("userfiles/"+userID+"_"+projectID+".xml"));
			//trace("open", file.nativePath);
			
			try 
			{
				var stream:FileStream = new FileStream(); 
				stream.openAsync(file, FileMode.WRITE);
				
			} catch (e:IOErrorEvent) 
			{
				this.dispatchEvent(new Event(Event.CANCEL));		
			}
			var outputString:String = '<?xml version="1.0" encoding="utf-8"?>\n'; 
			outputString += oxml.toXMLString(); 
			outputString = outputString.replace(/\n/g, File.lineEnding);
			stream.writeUTFBytes(outputString); 
			stream.close();		
			this.dispatchEvent(new Event(Event.COMPLETE));
		}
	}
}